<template>
	<view>
		<view v-if="renderDom[0].type === 'order'" :class="'custom-message ' + (isMine ? 'my-custom' : '')">
			<image class="custom-image" :src="renderDom[0].imageUrl"></image>
			<view class="custom-content">
				<view class="custom-content-title">{{ renderDom[0].title }}</view>
				<view class="custom-content-description">{{ renderDom[0].description }}</view>
				<view class="custom-content-price">{{ renderDom[0].price }}</view>
			</view>
		</view>
		<view v-if="renderDom[0].type === 'consultion'" :class="'custom-message ' + (isMine ? 'my-custom' : '')">
			<view class="custom-content">
				<view class="custom-content-title">{{ renderDom[0].title }}</view>
				<view v-for="(item, index) in renderDom[0].item" :key="index" class="custom-content-description"
					:id="item.key">{{ item.key }}</view>
				<view class="custom-content-description">{{ renderDom[0].description }}</view>
			</view>
		</view>
		<view v-if="renderDom[0].type === 'evaluation'" :class="'custom-message ' + (isMine ? 'my-custom' : '')">
			<view class="custom-content">
				<view class="custom-content-title">{{ renderDom[0].title }}</view>
				<view class="custom-content-score">
					<image v-for="(item, index) in renderDom[0].score" :key="index" class="score-star"
						src="/static/static/images/star.png"></image>
				</view>
				<view class="custom-content-description">{{ renderDom[0].description }}</view>
			</view>
		</view>
		<view v-if="renderDom[0].type === 'group_create'" :class="'custom-message ' + (isMine ? 'my-custom' : '')">
			<view class="custom-content-text">{{ renderDom[0].text }}</view>
		</view>
		<view v-if="renderDom[0].type === 'c2cCalling' || renderDom[0].type === 'groupCalling'"
			:class="'custom-message ' + (isMine ? 'my-custom' : '')">
			<view class="custom-content-text">{{ renderDom[0].text }}</view>
		</view>
		<view v-if="renderDom[0].type === 'hongb'" class="hongb">
			<!-- <view class="message-body-span-text">{{ renderDom[0].text }}</view> -->
			<!-- renderDom[0].number>=1判断是否领取完 -->
			<view class="hongb" v-if="renderDom[0].number >= 1" @click="tanc(renderDom[0].messagew)">
				<image src="/static/IM/red-envelope.png" mode="">
				</image>
			</view>
			<view class="hongb" v-else @click="tanc(renderDom[0].messagew)">
				<image src="/static/IM/lingquw.png" mode="">
				</image>
			</view>
		</view>
		<u-popup v-model="show" mode="center" height="750" width="550" border-radius="30">
			<view class="open-redenvelope">
				<view class="top">
					<view class="close-btn">
						<view class="icon close"></view>
					</view>
					<image :src="renderDom[0].avatar"></image>
				</view>
				<view class="from">来自{{ renderDom[0].nick }}</view>
				<view class="blessing">恭喜发财,剩余个数{{ renderDom[0].number }}</view>
				<view class="money">{{ suijmoney }}</view>
				<view class="showDetails" @click="toHongbx(renderDom[0].messagew)">
					查看领取详情 <view class="icon to"></view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
import {
	formateTime,
} from '../../../base/common.js';
import {
	getPrice,
	sendPrice
} from '@/network/api.js'
export default {
	data() {
		return {
			show: false,
			// 每次生成随机金额
			suijmoney: 0,
			// 判断是否重复领取
			pandu: false,
			// 领取红包id
			ids: ''
		};
	},
	components: {},
	props: {
		message: {
			type: Object,
			default: () => { }
		},
		isMine: {
			type: Boolean,
			default: true
		}
	},
	watch: {
		message: {
			handler: function (newVal) {
				this.setData({
					message: newVal,
					renderDom: this.parseCustom(newVal)
				});
			},
			immediate: true,
			deep: true
		}
	},
	methods: {
		// 领取红包
		getPriceRe() {
			let data = {
				id: this.ids
			}
			getPrice(data).then(res => {
				console.log(res, '领取红包结果')
			})
		},
		// 生成随机红包
		getRandomAmount(totalAmount, totalPeople) {
			const minAmount = 0.01; // 最小金额，单位为元
			const maxAmount = totalAmount / totalPeople * 2; // 最大金额，单位为元

			// 生成随机金额
			const randomAmount = Math.random() * (maxAmount - minAmount) + minAmount;
			const amount = Math.floor(randomAmount * 100) / 100; // 保留两位小数
			return amount;
		},
		// 弹出红包并计算每次随机红包金额
		async tanc(message) {
			console.log(JSON.parse(message.payload.data), '红包详情')
			await this.bof(1)
			const hongbDa = JSON.parse(message.payload.data)
			// 判断是否重复领取,true是,false否
			let eq = await this.geinfo(hongbDa.infoArr)
			// 判断此红包是否到期,如果小于结束时间可以领取，否则无法领取
			let timestampInSeconds = Math.floor(Date.now() / 1000);
			let is_linqu = false
			if (hongbDa.give.endtime <= timestampInSeconds) {
				is_linqu = true
			} else {
				is_linqu = false
			}
			console.log(is_linqu, '红包是否过期')
			// console.log(timestampInSeconds);
			// 判断红包大于1的时候才能产生随机红包
			if (hongbDa.number >= 1 && !eq && !is_linqu) {
				this.show = !this.show
				const totalAmount = hongbDa.extension; // 总金额，单位为元
				const totalPeople = hongbDa.number; // 总人数
				// 剩余最后一个红包
				// if (hongbDa.number == 1) {
					// 判断最后一个数是否有小数，个人红包没有小数，群红包有小数
					// if (hongbDa.extension % 1 !== 0) {
					// 	// 有小数
					// 	this.suijmoney = hongbDa.extension.toFixed(2)
					// } else {
						// 没有小数
						// this.suijmoney = hongbDa.extension
					// }
					// hongbDa.extension = 0
				// } else {
					// 每次生成随机金额
					// this.suijmoney = this.getRandomAmount(totalAmount, totalPeople)
					this.suijmoney = totalAmount
					hongbDa.extension = hongbDa.extension
				// }

				// 获取个人信息
				await uni.$TUIKit.getMyProfile().then((res) => {
					// console.log(res, '成功个人信息')
					hongbDa.infoArr.push({
						avatar: res.data.avatar, //领取者红包头像
						nick: res.data.nick, //领取红包者名称
						money: this.suijmoney, //领取红包金额
						time: this.time(res.data.lastUpdatedTime),
						userID: res.data.userID //领取红包者id
					})
				}).catch((error) => {
					// console.log(error, '报错个人信息')
				})

				// 每次使红包减1
				hongbDa.number--
				const bing = JSON.stringify(hongbDa)
				message.payload.data = bing

				await uni.$TUIKit.modifyMessage(message).then((res) => {
					// 成功变更后请求领取红包接口
					this.ids = hongbDa.give.id
					this.getPriceRe()
					console.log(res, '成功变更')
				}).catch((error) => {
					// console.log(error, '报错变更')
				})
			} else {
				this.toHongbx(this.renderDom[0].messagew)
			}
		},
		// 收取红包音频
		bof(type) {
			var music = null;
			music = uni.createInnerAudioContext(); //创建播放器对象
			// music.src ='http://www.jikehj.com/musical.mp3'; // static文件夹下的音频
			music.src = ''; // static文件夹下的音频
			if (type == 1) {
				music.play(); //执行播放
			} else {
				music.onEnded(() => {
					//播放结束
					music = null;
				});
			}
		},
		// 获取个人信息并判断是否重复领取红包
		async geinfo(arr) {
			await uni.$TUIKit.getMyProfile().then((res) => {
				this.pandu = arr.some((i) => {
					return res.data.userID === i.userID
				})
			}).catch((error) => {
				// console.log(error, '报错个人信息')
			})
			return this.pandu;
		},
		// 时间戳转换为时间
		time(timestamp) {
			const date = new Date(timestamp); // 将时间戳转换为 Date 对象
			const year = date.getFullYear(); // 获取年份
			const month = date.getMonth() + 1; // 获取月份（注意加一）
			const day = date.getDate(); // 获取日期
			const hour = date.getHours(); // 获取小时
			const minute = date.getMinutes(); // 获取分钟
			const second = date.getSeconds(); // 获取秒数
			const formattedDate = `${year}-${month}-${day} ${hour}:${minute}:${second}`; //拼接成格式化后的日期字符串
			return formattedDate;
		},
		// 解析音视频通话消息
		extractCallingInfoFromMessage(message) {
			const callingmessage = JSON.parse(message.payload.data);
			if (callingmessage.businessID !== 1) {
				return '';
			}
			const objectData = JSON.parse(callingmessage.data);
			switch (callingmessage.actionType) {
				case 1: {
					if (objectData.call_end >= 0 && !callingmessage.groupID) {
						return `通话时长：${formateTime(objectData.call_end)}`;
					}
					if (callingmessage.groupID) {
						return '结束群聊';
					}
					if (objectData.data && objectData.data.cmd === 'switchToAudio') {
						return '切换语音通话';
					}
					if (objectData.data && objectData.data.cmd === 'switchToVideo') {
						return '切换视频通话';
					}
					return '发起通话';
				}
				case 2:
					return '取消通话';
				case 3:
					if (objectData.data && objectData.data.cmd === 'switchToAudio') {
						return '切换语音通话';
					}
					if (objectData.data && objectData.data.cmd === 'switchToVideo') {
						return '切换视频通话';
					}
					return '已接听';
				case 4:
					return '拒绝通话';
				case 5:
					if (objectData.data && objectData.data.cmd === 'switchToAudio') {
						return '切换语音通话';
					}
					if (objectData.data && objectData.data.cmd === 'switchToVideo') {
						return '切换视频通话';
					}
					return '无应答';
				default:
					return '';
			}
		},
		parseCustom(message) {
			// 约定自定义消息的 data 字段作为区分，不解析的不进行展示
			if (message.payload.data === 'order') {
				const extension = JSON.parse(message.payload.extension);
				const renderDom = [{
					type: 'order',
					name: 'custom',
					title: extension.title || '',
					imageUrl: extension.imageUrl || '',
					price: extension.price || 0,
					description: message.payload.description
				}];
				return renderDom;
			} // 客服咨询

			if (message.payload.data === 'consultion') {
				const extension = JSON.parse(message.payload.extension);
				const renderDom = [{
					type: 'consultion',
					title: extension.title || '',
					item: extension.item || 0,
					description: extension.description
				}];
				return renderDom;
			} // 服务评价

			if (message.payload.data === 'evaluation') {
				const extension = JSON.parse(message.payload.extension);
				const renderDom = [{
					type: 'evaluation',
					title: message.payload.description,
					score: extension.score,
					description: extension.comment
				}];
				return renderDom;
			} // 群消息解析
			// 群消息解析
			if (message.payload.data === 'group_create') {
				const renderDom = [{
					type: 'group_create',
					text: message.payload.extension
				}];
				return renderDom;
			}
			// 音视频通话消息解析
			const callingmessage = JSON.parse(message.payload.data);

			if (callingmessage.businessID === 1) {
				if (message.conversationType === 'GROUP') {
					if (message.payload.data.actionType === 5) {
						message.nick = message.payload.data.inviteeList ? message.payload.data.inviteeList.join(',') :
							message.from;
					}
					const _text = this.extractCallingInfoFromMessage(message);
					const groupText = `${_text}`;
					const renderDom = [{
						type: 'groupCalling',
						text: groupText,
						userIDList: []
					}];
					return renderDom;
				}
				if (message.conversationType === 'C2C') {
					const c2cText = this.extractCallingInfoFromMessage(message);
					const renderDom = [{
						type: 'c2cCalling',
						text: c2cText
					}];
					return renderDom;
				}
			}

			if (message.payload.data === 'group_create') {
				const renderDom = [{
					type: 'group_create',
					text: message.payload.extension
				}];
				return renderDom;
			}

			const hongbDa = JSON.parse(message.payload.data)
			if (hongbDa.data === 'hongb') {
				const renderDom = [{
					type: 'hongb', //类型
					text: hongbDa.extension, //红包金额
					number: hongbDa.number, //红包个数
					avatar: message.avatar, //红包发送者头像
					nick: message.nick, //红包发送者名称
					messagew: message, //此条消息数据
					infoArr: hongbDa.infoArr //领取红包用户
				}];
				return renderDom;
			}

			return [{
				type: 'notSupport',
				text: '[自定义消息]'
			}];
		},
		// 跳转到红包详情
		toHongbx(message) {
			let data = {
				dangqMoney: this.suijmoney, //个人所得红包金额
				messageew: message
			}
			console.log(message, '红包详情')
			uni.navigateTo({
				url: '/pages/subpackage/IM/HM-details/HM-details?data=' + JSON.stringify(data)
			})
		}
	}
};
</script>
<style lang="scss">
@import './index.css';

.hongb {
	width: 300rpx;
	height: 400rpx;

	>image {
		position: relative;
		width: 100%;
		height: 100%;

		>text {
			display: block;
			position: absolute;
			top: -100px;
			left: 0;
			right: 0;
			bottom: 30rpx;
		}
	}
}

.open-redenvelope {
	width: 100%;
	height: 100%;
	background-color: #cf3c35;
	position: relative;

	.top {
		width: 100%;
		background-color: #fe5454;
		display: flex;
		justify-content: center;
		flex-wrap: wrap;
		border-radius: 0 0 100% 100%;
		box-shadow: inset 0 -20upx 0 #9c1712;

		.close-btn {
			width: 100%;
			height: 80upx;
			display: flex;
			justify-content: flex-end;
			margin-bottom: 30upx;

			.icon {
				color: #9c1712;
				margin-top: 10upx;
				margin-right: 10upx;
			}
		}

		image {
			width: 130upx;
			height: 130upx;
			border: solid 12upx #cf3c35;
			border-radius: 100%;

			margin-bottom: -65upx;
		}

		margin-bottom: 65upx;
	}

	.from,
	.blessing,
	.money,
	.showDetails {
		width: 100%;
		padding: 5upx 5%;
		display: flex;
		justify-content: center;
		font-size: 32upx;
		color: #fff;
	}

	.money {
		font-size: 100upx;
		color: #f8d757;
		display: flex;
		padding-top: 20upx;
	}

	.showDetails {
		position: absolute;
		bottom: 20upx;
		align-items: center;
		font-size: 28upx;
		color: #f8d757;

		.icon {
			font-size: 26upx;
			color: #f8d757;
		}
	}
}
</style>